import {Shader} from "../../pages/test_math/src/Shader";


function createShader(gl:WebGL2RenderingContext,shaderType:GLenum, source:string) {
    let shader = gl.createShader(shaderType) as WebGLShader;
    if (shader <= 0) {
        throw `create shaderType:${shaderType} error!`;
    }
    gl.shaderSource(shader, source);
    gl.compileShader(shader);

    let msg = gl.getShaderInfoLog(shader) as string;
    if (msg && msg.length > 0) {
        throw msg;
    }
    return shader;
}

export function buildShader(gl:WebGL2RenderingContext,vs:string, fs:string) {
    let vsShader = createShader(gl,gl.VERTEX_SHADER, vs);
    let fsShader = createShader(gl,gl.FRAGMENT_SHADER, fs);
    let program = gl.createProgram() as WebGLProgram;
    gl.attachShader(program, vsShader);
    gl.attachShader(program, fsShader);
    gl.linkProgram(program);

    if (!gl.getShaderParameter(vsShader, gl.COMPILE_STATUS)) {
        let error_str = gl.getShaderInfoLog(vsShader);
        console.error('vs_shader:',error_str);
    }
    if (!gl.getShaderParameter(fsShader, gl.COMPILE_STATUS)) {
        let error_str = gl.getShaderInfoLog(fsShader);
        console.error('fs_shader:',error_str);
    }

    gl.deleteShader(vsShader);
    gl.deleteShader(fsShader);

    if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
        let error_str = gl.getProgramInfoLog(program);
        console.error('link_error:',error_str);
    }
    return  new Shader(gl,program);
}


